import {AfterViewInit, Component, inject, OnInit, Renderer2} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {EventbusService} from "../../services/eventbus.service";
import {AuthService} from "../../services/auth.service";
import {StorageService} from "../../services/storage.service";
import {Router} from "@angular/router";
import {AlertService} from "../../services/alert.service";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
export class LoginComponent implements OnInit,AfterViewInit{

  validateForm!: FormGroup;
  username:string;
  pass:string;
  private eventbus:EventbusService=inject(EventbusService);

  constructor(private fb: FormBuilder,private authservice:AuthService
    ,private storage:StorageService
    ,private alertservice:AlertService
    ,private router:Router,
              private renderer: Renderer2) {
  }

  ngAfterViewInit(): void {

    // const element = document.getElementById('bg')// Select the target element
    // //const imageUrl = this.sitemanageservice.getCoverPicByPositonURL+'LOGIN_WEB_SCREEN';
    // // this.renderer.setStyle(element, 'background-image', `url(${imageUrl})`);
    // this.renderer.setStyle(element,'background-size','cover');
    // this.renderer.setStyle(element,'background-position','center');
    // this.renderer.setStyle(element,'height','100%')
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required]],
      remember: [true]
    });
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(i)) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    }
    if(this.validateForm.valid){
      this.authservice.loginByPassword(this.validateForm.get("userName")?.value,this.validateForm.get("password")?.value)
        .then((data:any)=>{
          //console.dir(data);
          if(data.msg=='ok'){
            //console.log("准备存储");
            this.storage.set("TOKEN",data.obj)
              .then(()=>{

                // this.eventbus.publish('LOGIN_SUCCESS','');
                this.router.navigate(['/admin']);
              })



          }
          else if(data.msg=='locked'){
            this.alertservice.showWarn('账号被锁定，请与管理员联系');
          }
          else if(data.msg=='error'){
            this.alertservice.showError('账户异常，请与管理员联系');
          }



          else if(data.msg=='passerror') {
            this.alertservice.showWarn('用户名或是密码错误，清核实');
          }
        })
      //console.log(this.validateForm.get("userName").value);
    }

  }








}
